#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "cJSON.h"


using namespace std;

void transer(char *data);

int main(){

    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;
    char buf[1024];

    // create a TCP socket
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        cerr << "Failed to create socket\n";
        return -1;
    }

    // bind to a specific IP address and port
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("192.168.1.231"); // bind to a specific IP address
    server_addr.sin_port = htons(/*12345*/65300); // use port in USR-TCP232-304 <Serial Port>
//    client_addr.sin_addr.s_addr = inet_addr("192.168.1.230");
//    client_addr.sin_port = htons(/*12345*/65300);
    client_addr.sin_addr.s_addr = inet_addr("192.168.1.202");
    client_addr.sin_port = htons(65300);
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        cerr << "Failed to bind to port\n";
        return -1;
    }

    // listen for incoming connections
    if (listen(server_fd, 5) < 0) {
        cerr << "Failed to listen for connections\n";
        return -1;
    }

    cout << "Waiting for connections...\n";

    while (1) {
        // accept a new connection
        client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_fd < 0) {
            cerr << "Failed to accept connection\n";
            continue;
        }

        cout << "Accepted connection from " << inet_ntoa(client_addr.sin_addr) << "\n";

        while (1) {
            // read data from the client
            int n = read(client_fd, buf, sizeof(buf)-1);
            if (n < 0) {
                cerr << "Failed to read data from client\n";
                break;
            } else if (n == 0) {
                cout << "Client closed the connection\n";
                break;
            } else {
                buf[n] = '\0';
                cout << "Received data: " << buf << "\n";
                //do something
                transer(buf);
                std::cout<<"处理后的函数（collect里的输出）:"<<std::endl;
                std::cout<<buf<<std::endl;
            }
        }

        close(client_fd);
        cout << "Closed connection with " << inet_ntoa(client_addr.sin_addr) << "\n";
    }

    close(server_fd);

    return 0;
}

void transer(char *data){
    //模拟令牌
    cJSON* cjson_token = NULL;
    cjson_token= cJSON_CreateObject();
    cJSON_AddNumberToObject(cjson_token, "coke", 2);
    cJSON_AddStringToObject(cjson_token, "name", "name");
    cJSON_AddStringToObject(cjson_token, "password", "password");
    char* token = cJSON_Print(cjson_token);
    //原始数据
    cJSON* cjson_data = NULL;
    cjson_data = cJSON_CreateObject();
    cJSON_AddNumberToObject(cjson_data,"windSpeed",0.0);
    cJSON_AddNumberToObject(cjson_data, "windScale", 0.0);
    cJSON_AddNumberToObject(cjson_data, "windDirection", 45);
    cJSON_AddNumberToObject(cjson_data, "ambientTemperature", 26.14);
    cJSON_AddNumberToObject(cjson_data, "ambientHumidity", 47.56);
    cJSON_AddNumberToObject(cjson_data, "pressure", 100.90);
    cJSON_AddNumberToObject(cjson_data, "rainfall", 0.0);
    cJSON_AddNumberToObject(cjson_data, "PM2.5", 31);
    cJSON_AddNumberToObject(cjson_data, "PM10", 40);
    cJSON_AddNumberToObject(cjson_data, "lightIntensity", 396);
//    std::cout << "原始数据：" << std::endl;
    data = cJSON_Print(cjson_data);
//    std::cout << oj << std::endl;
    //开始处理
    //第一步，解析
    cJSON *cjson_=NULL;
    cjson_=cJSON_CreateObject();
    cJSON* cjson_temperature = NULL;
    cJSON* cjson_humidity = NULL;
    cJSON* cjson_speed = NULL;
    cJSON* cjson_direction = NULL;
    cJSON* cjson_rain;
    cJSON* cjson_sunlight = NULL;
    cJSON* cjson_pm25 = NULL;
    cJSON* cjson_pm10 = NULL;
    cjson_ = cJSON_Parse(data);
    cjson_temperature = cJSON_GetObjectItem(cjson_, "ambientTemperature");
    cjson_humidity = cJSON_GetObjectItem(cjson_, "ambientHumidity");
    cjson_speed = cJSON_GetObjectItem(cjson_, "windSpeed");
    cjson_direction = cJSON_GetObjectItem(cjson_, "windDirection");
    cjson_rain = cJSON_GetObjectItem(cjson_, "rainfall");
    cjson_sunlight = cJSON_GetObjectItem(cjson_, "lightIntensity");
    cjson_pm25 = cJSON_GetObjectItem(cjson_, "PM2.5");
    cjson_pm10 = cJSON_GetObjectItem(cjson_, "PM10");
    //第二步，封装
    cJSON* cjson_new = NULL;
    cjson_new=cJSON_CreateObject();
    cJSON_AddNumberToObject(cjson_new, "code", 5);
    cJSON_AddStringToObject(cjson_new, "token", token);
    std::cout<<"token:"<<token<<std::endl;
    cJSON_AddNumberToObject(cjson_new, "station", 9090);
    int time_;
    time_t t;
    time_ = time(&t);
    cJSON_AddNumberToObject(cjson_new, "time", time_);
    cJSON_AddNumberToObject(cjson_new, "temperature", cjson_temperature->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "humidity", cjson_humidity->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "speed", cjson_speed->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "direction", cjson_direction->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "rain", cjson_rain->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "sunlight", cjson_sunlight->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "pm25", cjson_pm10->valuedouble);
    cJSON_AddNumberToObject(cjson_new, "pm10", cjson_pm25->valuedouble);
//    char *buf = NULL;
//    std::cout<<"直接用cjson_Print()输出"<<std::endl;
//    std::cout<<cJSON_Print(cjson_new)<<std::endl;
    data=cJSON_Print(cjson_new);
    std::cout << "处理后的数据(transer函数里面的输出)" << std::endl;
    std::cout << data<< std::endl;
    cJSON_Delete(cjson_data);
    cJSON_Delete(cjson_new);
}